﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using EtlComm;
using TaskToLineUp;
using ETLDispatcher;
using ETLHandler;
using DevComponents.DotNetBar.Controls;
using System.Runtime.InteropServices;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Xml;


namespace ChinaPetroETL
{



    public partial class frmMonitor : Office2007Form
    {
        ClientBaseLog log = LogFactory.CreateLog<ClientBaseLog>();
        DataSet dsxml = new DataSet();
        DataSet dssk = new DataSet();
        int a1;
     
        DataTable dsstation = new DataTable();
        private Point p;
        //是否打开颜色效果
        private Boolean isopencolor = true;


        public frmMonitor()
        {
            InitializeComponent();
            log.OnTaskProcess += new EtlProcess(log_OnTaskProcess);
        }




        void log_OnTaskProcess(object sender, EtlEventArgs e)
        {
            this.Invoke((EventHandler)delegate
            {
                try
                {
                    string DProcess = e.DProcess.ToString();
                    string StationID = e.StationID.ToString();
                    string TaskID = e.TaskID;
                    Boolean isexit = false;
                    Boolean iscomple = false;
                    //更新增加列到dsstation,展开树时显示他的执行状态
                    
                    for (int j = 0; j < dsstation.Rows.Count; j++)
                    {
                        //如果dsstation中已经存在StationID和TaskID更改状态值
                        if (dsstation.Rows[j]["StationID"].ToString() == StationID && dsstation.Rows[j]["TaskID"].ToString() == TaskID)
                        {
                            
                            dsstation.Rows[j]["DProcess"] = DProcess;


                            for (int i = 0; i < this.dx_data.Rows.Count; i++)
                            {
                                if (this.dx_data.Rows[i].Cells["加油站ID"].Value.ToString() == StationID.ToString())
                                {
                                    a1 = Convert.ToInt16(TaskID) * (100 / Convert.ToInt16(this.dx_data.Rows[i].Cells["任务数"].Value));
                                    this.dx_data.Rows[i].Cells["diaoduzhuangtai"].Value = a1;


                                    //如果任务中有一个不是完成的 则现在颜色状态为第一个非完成状态的状态
                                    string expression;
                                    expression = "StationID='" + StationID + "'";//便利条件
                                    DataRow[] foundRows;
                                    foundRows = dsstation.Select(expression);
                                    if (e.DProcess.ToString() == "COMPLETED")
                                    {

                                        for (int l = 0; l < foundRows.Length; l++)
                                        {
                                            if (foundRows[l][2].ToString() != "COMPLETED" && foundRows[l][2].ToString() != "")
                                            {
                                                this.dx_data.Rows[i].Cells["总体状态"].Value = TransProcessToChinese(foundRows[l][2].ToString());
                                                iscomple = false;
                                                break;
                                            }
                                            else
                                            {
                                                iscomple = true;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        this.dx_data.Rows[i].Cells["总体状态"].Value = TransProcessToChinese(e.DProcess.ToString());
                                    }
                                    if (iscomple)
                                    {
                                        this.dx_data.Rows[i].Cells["总体状态"].Value = TransProcessToChinese(e.DProcess.ToString());
                                    }

                                  
                                }
                            }
                          
                            isexit = true;
                            break;
                        }
                       // isexit = false;
                    }
                    //如果不存在 增加状态值
                    if (!isexit)
                    {
                        DataRow dr = dsstation.NewRow();
                        dr["StationID"] = StationID;
                        dr["TaskID"] = TaskID;
                        dr["DProcess"] = DProcess;
                        dsstation.Rows.Add(dr);
                        for (int i = 0; i < this.dx_data.Rows.Count; i++)
                        {
                            if (this.dx_data.Rows[i].Cells["加油站ID"].Value.ToString() == StationID.ToString())
                            {
                                a1 = Convert.ToInt16(TaskID) * (100 / Convert.ToInt16(this.dx_data.Rows[i].Cells["任务数"].Value));
                                this.dx_data.Rows[i].Cells["diaoduzhuangtai"].Value = a1;


                                //如果任务中有一个不是完成的 则现在颜色状态为第一个非完成状态的状态
                                string expression;
                                expression = "StationID='" + StationID + "'";//便利条件
                                DataRow[] foundRows;    
                                foundRows = dsstation.Select(expression);
                                if (e.DProcess.ToString() == "COMPLETED")
                                {

                                    for (int l = 0; l < foundRows.Length; l++)
                                    {
                                        if (foundRows[l][2].ToString() != "COMPLETED" && foundRows[l][2].ToString()!="")
                                        {
                                            this.dx_data.Rows[i].Cells["总体状态"].Value = TransProcessToChinese(foundRows[l][2].ToString());
                                            iscomple = false;

                                            break;
                                        }
                                        else 
                                        {
                                            iscomple = true;
                                        }
                                    }
                                }
                                else 
                                {
                                    this.dx_data.Rows[i].Cells["总体状态"].Value = TransProcessToChinese(e.DProcess.ToString());//e.DProcess;
                                }
                                if (iscomple)
                                {
                                    this.dx_data.Rows[i].Cells["总体状态"].Value = TransProcessToChinese(e.DProcess.ToString());
                                }


                            }
                        }
                    }
                   

                        X1Progress_Initialize();
                    
                }
                catch (System.Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }

            });        
        }
        /// <summary>
        /// 将执行的状态条件翻译成对应的中文
        /// </summary>
        /// <param name="dp"></param>
        /// <returns></returns>
        private string TransProcessToChinese(string dp)
        {
            string strReturn = ""; 
            switch (dp.ToString())
            {
                case "WAIT":
                    strReturn = "等待调度";
                    break;
                case "EXCUTE":
                    strReturn = "执行任务";
                    break;
                case "COMPLETED":
                    strReturn = "成功完成";
                    break;
                case "STOP":
                    strReturn = "调度终止";
                    break;
                case "FAIL":
                    strReturn = "任务失败";
                    break;
                case "COMPLETEDERROR":
                    strReturn = "成功有失败";
                    break;
            }
            return strReturn;
        }
        private void InitTask()
        {

            try
            {
                //获取任务列表
                IList<StationObject> lstSO = TaskQueuer.StationObjectList;
                IEDTDispatcher disp = new EtlDispatcher();
                disp.Active = true;
                disp.log = log;
                //调度任务
                disp.Initialize(lstSO);
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

        }


        private void frmMonitor_Load(object sender, EventArgs e)
        {

            loadgirdview();

        }
        DataSet getxml(string xmlName)
        {
            string xml = ""; ;
            ServiceReference1.EtlServicesClient client = new ChinaPetroETL.ServiceReference1.EtlServicesClient();
            BinaryFormatter b = new BinaryFormatter();


            MemoryStream ms = new MemoryStream();
            if (xmlName == "TaskInfo.xml")
            {
                 xml = client.GetTaskInfo();
            }
            else if (xmlName == "StationTaskRunInfo.xml")
            {
                xml = client.GetStationTaskRunInfo();
            }
            else { 
            
            }


            string a = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n";
            xml = a + xml;

            StringReader StrStream = null;
            XmlTextReader Xmlrdr = null;
            try
            {
                DataSet ds1 = new DataSet();

                StrStream = new StringReader(xml);

                Xmlrdr = new XmlTextReader(StrStream);

                ds1.ReadXml(Xmlrdr);
                return ds1;

            }
            catch (Exception e)
            {
                throw e;

            }
            finally
            {
                //释放资源
                if (Xmlrdr != null)
                {
                    Xmlrdr.Close();
                    StrStream.Close();
                }
            }
        }
        void loadgirdview()
        {
            #region
           


            //b.Serialize(ms, xml);
              dssk.Clear();
              dssk=getxml("TaskInfo.xml");

            //dssk.ReadXml("TaskInfo.xml");
            //为dssk赋值 在加载TREE时要用到

            //为ds创建列
            DataTable ds = new DataTable();


            DataColumn dc = new DataColumn();
            dc.ColumnName = "序号";
            dc.DataType = Type.GetType("System.Int32");
            // dt为你DataTable的实例
            ds.Columns.Add(dc);

            DataColumn dc4 = new DataColumn();
            dc4.ColumnName = "加油站Id";
            dc4.DataType = Type.GetType("System.String");
            // dt为你DataTable的实例
            ds.Columns.Add(dc4);

            DataColumn dc1 = new DataColumn();
            dc1.ColumnName = "加油站名称";
            dc1.DataType = Type.GetType("System.String");
            // dt为你DataTable的实例
            ds.Columns.Add(dc1);

            DataColumn dc2 = new DataColumn();
            dc2.ColumnName = "调度频率";
            dc2.DataType = Type.GetType("System.String");
            // dt为你DataTable的实例\

            ds.Columns.Add(dc2);
            DataColumn dc3 = new DataColumn();
            dc3.ColumnName = "任务数";
            dc3.DataType = Type.GetType("System.String");
            // dt为你DataTable的实例
            ds.Columns.Add(dc3);

            DataColumn dc5 = new DataColumn();
            dc5.ColumnName = "调度状态";
            dc5.DataType = Type.GetType("System.Int32");
            // dt为你DataTable的实例
            ds.Columns.Add(dc5);


            DataColumn dc6 = new DataColumn();
            dc6.ColumnName = "调度日志";
            dc6.DataType = Type.GetType("System.String");
            // dt为你DataTable的实例
            ds.Columns.Add(dc6);

            DataColumn dc7 = new DataColumn();
            dc7.ColumnName = "任务调度查看";

            dc7.DataType = Type.GetType("System.String");
            // dt为你DataTable的实例
            ds.Columns.Add(dc7);


            DataColumn dc8 = new DataColumn();
            dc8.ColumnName = "是否停用";

            dc8.DataType = Type.GetType("System.String");
            // dt为你DataTable的实例
            ds.Columns.Add(dc8);

            DataColumn dc9 = new DataColumn();
            dc9.ColumnName = "总体状态";

            dc9.DataType = Type.GetType("System.String");
            // dt为你DataTable的实例
            ds.Columns.Add(dc9);


            //dsxml.ReadXml("StationTaskRunInfo.xml");\
           
            dsxml.Clear();
            dsxml = getxml("StationTaskRunInfo.xml");
            #endregion

            #region 调度状态


            DataColumn dcs = new DataColumn();
            dcs.ColumnName = "StationID";
            dcs.DataType = Type.GetType("System.String");
            // dt为你DataTable的实例
            dsstation.Columns.Add(dcs);

            DataColumn dcs1 = new DataColumn();
            dcs1.ColumnName = "TaskID";
            dcs1.DataType = Type.GetType("System.String");
            // dt为你DataTable的实例
            dsstation.Columns.Add(dcs1);

            DataColumn dcs2 = new DataColumn();
            dcs2.ColumnName = "DProcess";
            dcs2.DataType = Type.GetType("System.String");
            // dt为你DataTable的实例
            dsstation.Columns.Add(dcs2);
            #endregion


            for (int i = 0; i < dsxml.Tables[0].Rows.Count; i++)
            {
                ds.Rows.Add();
                ds.Rows[i]["序号"] = i + 1;
                ds.Rows[i]["加油站Id"] = dsxml.Tables[0].Rows[i]["StationID"].ToString();
                ds.Rows[i]["加油站名称"] = dsxml.Tables[0].Rows[i]["StationName"].ToString();
                ds.Rows[i]["调度频率"] = dsxml.Tables[0].Rows[i]["Interval"].ToString();
                ds.Rows[i]["调度状态"] = 0;
                int m = 0;
                for (int j = 0; j < dsxml.Tables[1].Rows.Count; j++)
                {
                    if (dsxml.Tables[0].Rows[i]["Station_Id"].ToString() == dsxml.Tables[1].Rows[j]["Station_Id"].ToString())
                    {
                        m++;
                    }
                }
                ds.Rows[i]["任务数"] = m.ToString();
                ds.Rows[i]["调度日志"] = "调度日志";
                ds.Rows[i]["任务调度查看"] = "任务调度查看";
                ds.Rows[i]["总体状态"] = "";
                if (dsxml.Tables[0].Rows[i]["IsActive"].ToString() == "1")
                {
                    ds.Rows[i]["是否停用"] = "否";
                }
                else
                {
                    ds.Rows[i]["是否停用"] = "是";
                }
            }

           
            this.dx_data.DataSource = ds.DefaultView;


        }


        private void X1Progress_Initialize()
        {
            DataGridViewProgressBarXColumn pb =
                dx_data.Columns["diaoduzhuangtai"] as DataGridViewProgressBarXColumn;



            if (pb != null)
                pb.BeforeCellPaint += X1Progress_BeforeCellPaint;
        }

        void X1Progress_BeforeCellPaint(object sender, BeforeCellPaintEventArgs e)
        {
           
                DataGridViewProgressBarXColumn pbc =
                    sender as DataGridViewProgressBarXColumn;
               
                if (pbc != null)
                {
                    try
                    {
              
                      

                        switch (pbc.Value)
                        {

                            case 100:
                                pbc.Text = "100%";

                                break;
                            case 0:
                                pbc.Text = "0%";

                                break;

                            default:

                                pbc.Text = pbc.Value + "%";

                                break;
                        }
                        #region 加颜色
                        if (isopencolor)
                        {
                            switch (this.dx_data.Rows[e.RowIndex].Cells["总体状态"].Value.ToString())
                            {

                                case "等待调度"://等待调度

                                    pbc.ColorTable = eProgressBarItemColor.Paused;
                                    break;

                                case "成功完成"://任务正确完成

                                    pbc.ColorTable = eProgressBarItemColor.Normal;
                                    break;
                                case "调度终止"://调度终止

                                    pbc.ColorTable = eProgressBarItemColor.Paused;
                                    break;
                                case "任务失败"://任务执行失败


                                    pbc.ColorTable = eProgressBarItemColor.Error;
                                    break;
                                case "成功有失败"://任务完成但是有错误发生

                                    pbc.ColorTable = eProgressBarItemColor.Error;
                                    break;
                                case "执行任务":
                                    pbc.ColorTable = eProgressBarItemColor.Paused;
                                    break;
                                default:

                                    break;

                            }
                        }
                    #endregion 加颜色END

                    }
                    catch
                    {

                    }
                }
        
           
        }

        private void dataGridViewX1_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {

        }

        private void dataGridViewX1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (this.dx_data.Columns[e.ColumnIndex].HeaderText == "查看日志")
                {
                    string a = System.Windows.Forms.Application.StartupPath + " \\log\\" + this.dx_data.Rows[e.RowIndex].Cells["加油站ID"].Value + ".log";

                    System.Diagnostics.Process.Start("explorer.exe", System.Windows.Forms.Application.StartupPath + " \\log\\" + this.dx_data.Rows[e.RowIndex].Cells["加油站ID"].Value + ".log");
                }
                else if (this.dx_data.Columns[e.ColumnIndex].HeaderText == "任务调度查看")
                {
                    showtree(this.dx_data.Rows[e.RowIndex].Cells["加油站ID"].Value.ToString());
                }
                else
                {

                }
            }
            catch
            {
                // MessageBox.Show(elog.Message);

            }

        }
        void showtree(string ID)
        {
            string HaveParams = "";

            try
            {
              
                dsxml.Clear();
                dsxml = getxml("StationTaskRunInfo.xml");
              
                this.trvtaskinfo.Nodes[0].Nodes.Clear();
                if (p.Y > 585)
                {
                    this.panel1.Top = 585;
                }
                else
                {
                    this.panel1.Top = p.Y + 15;
                }

                string Station_Id = "";
                for (int n = 0; n < dsxml.Tables[0].Rows.Count; n++)
                {
                    if (dsxml.Tables[0].Rows[n]["StationID"].ToString() == ID)
                    {
                        Station_Id = dsxml.Tables[0].Rows[n]["Station_Id"].ToString();
                        break;
                    }
                }
                for (int m = 0; m < dsxml.Tables[1].Rows.Count; m++)
                {


                    if (dsxml.Tables[1].Rows[m]["Station_Id"].ToString() == Station_Id)//根据内置主键区分是否是从表数据
                    {
                        TreeNode td = new TreeNode();
                        td.Text = "任务" + dsxml.Tables[1].Rows[m]["TaskID"].ToString();
                        td.Name = "任务" + dsxml.Tables[1].Rows[m]["TaskID"].ToString();
                        this.trvtaskinfo.Nodes[0].Nodes.Add(td);


                        //  this.trvtaskinfo.Nodes[0].Nodes.Add("任务" + dsxml.Tables[1].Rows[m]["TaskID"].ToString());
                        //加载任务状态 动态TABLE



                        for (int j = 0; j < dssk.Tables[0].Rows.Count; j++)
                        {
                            if (dssk.Tables[0].Rows[j]["TaskID"].ToString() == dsxml.Tables[1].Rows[m]["TaskID"].ToString())
                            {
                                this.trvtaskinfo.Nodes[0].Nodes["任务" + dsxml.Tables[1].Rows[m]["TaskID"].ToString()].Nodes.Add("SQLStatement:" + dssk.Tables[0].Rows[j]["SQLStatement"].ToString());
                                this.trvtaskinfo.Nodes[0].Nodes["任务" + dsxml.Tables[1].Rows[m]["TaskID"].ToString()].Nodes.Add("Action:" + dssk.Tables[0].Rows[j]["Action"].ToString());


                                if (dssk.Tables[0].Rows[j]["HaveParams"].ToString() == "1")
                                {
                                    HaveParams = "是";
                                }
                                else
                                {
                                    HaveParams = "否";
                                }
                                this.trvtaskinfo.Nodes[0].Nodes["任务" + dsxml.Tables[1].Rows[m]["TaskID"].ToString()].Nodes.Add("HaveParams:" + HaveParams);
                                break;
                            }
                        }

                        this.trvtaskinfo.Nodes[0].Nodes["任务" + dsxml.Tables[1].Rows[m]["TaskID"].ToString()].Nodes.Add("StartTime:" + dsxml.Tables[1].Rows[m]["StartTime"].ToString());
                        this.trvtaskinfo.Nodes[0].Nodes["任务" + dsxml.Tables[1].Rows[m]["TaskID"].ToString()].Nodes.Add("EndTime:" + dsxml.Tables[1].Rows[m]["EndTime"].ToString());
                        for (int k = 0; k < dsstation.Rows.Count; k++)
                        {
                            if (dsstation.Rows[k]["StationID"].ToString() == ID && dsstation.Rows[k]["TaskID"].ToString() == dsxml.Tables[1].Rows[m]["TaskID"].ToString())
                            {
                                this.trvtaskinfo.Nodes[0].Nodes["任务" + dsxml.Tables[1].Rows[m]["TaskID"].ToString()].Nodes.Add("DProcess:" + dsstation.Rows[k]["DProcess"].ToString());
                                if (dsstation.Rows[k]["DProcess"].ToString() != "COMPLETED")
                                {
                                    this.trvtaskinfo.Nodes[0].Nodes["任务" + dsxml.Tables[1].Rows[m]["TaskID"].ToString()].BackColor = Color.Red;
                                }
                                else
                                {
                                    this.trvtaskinfo.Nodes[0].Nodes["任务" + dsxml.Tables[1].Rows[m]["TaskID"].ToString()].BackColor = Color.GreenYellow;
                                }
                                break;
                            }

                        }
                    }
                }
                this.trvtaskinfo.Nodes[0].Expand();
                this.panel1.Visible = true;
            }
            catch { }
        }

        private void trvtaskinfo_MouseLeave(object sender, EventArgs e)
        {
            this.trvtaskinfo.Visible = false;
        }

        private void dataGridViewX1_MouseDown(object sender, MouseEventArgs e)
        {
            try
            {
                p = new Point(e.X, e.Y);
            }
            catch { }
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
            this.panel1.Visible = false;
        }


    }

    public class sssslog : ClientBaseLog
    {
        public override bool WriteLog(string StationID, string TaskID, string loginfo)
        {
            return base.WriteLog(StationID, TaskID, loginfo);
        }
    }
}
